package com.mdc.mansion.core.modules.push;

import com.mdc.mansion.common.util.DateUtils;
import com.mdc.mansion.common.util.log.BusinessLogger;
import com.mdc.mansion.dataaccess.modules.basedata.dao.PushMessageDao;
import com.mdc.mansion.dataaccess.modules.basedata.entity.PushMessage;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class JPushService {
    @Resource
    private PushMessageDao pushMessageDao;
    @Resource
    private List<JPushToClientService> jPushToClientServices;

    private Logger LOGGER= LoggerFactory.getLogger(this.getClass());

    public void pushMessageToClient() {
       List<PushMessage> messageList= pushMessageDao.getCanSendMessage();
       if(CollectionUtils.isEmpty(messageList)){return;}
       for(PushMessage pushMessage:messageList){
           sendMessageToClient(pushMessage);
       }
    }

    private void sendMessageToClient(PushMessage pushMessage) {
        for(JPushToClientService jPushToClientService:jPushToClientServices){
            if(jPushToClientService.isSupport(pushMessage)){
                try{
                    jPushToClientService.sendToClient(pushMessage);
                    BusinessLogger.log("sendMessageToClient"+pushMessage.getId(),"成功");
                    pushMessage.setMessageStatus(PushMessage.MESSAGE_STATUS.SEND_SUCCESS.getVal());
                    LOGGER.info("sendMessageToClient"+pushMessage.getId()+"成功");
                }catch (Exception e){
                    BusinessLogger.log("sendMessageToClient"+pushMessage.getId(),"失败，case,"+ ExceptionUtils.getFullStackTrace(e));
                    pushMessage.setSendTimes(pushMessage.getSendTimes()+1);
                    pushMessage.setMessageStatus(PushMessage.MESSAGE_STATUS.SEND_FAIL.getVal());
                    String fullStackTrace = ExceptionUtils.getFullStackTrace(e);
                    if(StringUtils.length(fullStackTrace)>2000){
                        fullStackTrace=fullStackTrace.substring(0,2000);
                    }
                    pushMessage.setErrorReason(fullStackTrace);
                    LOGGER.info("sendMessageToClient"+pushMessage.getId()+"失败，case,"+ ExceptionUtils.getFullStackTrace(e));
                }
                pushMessageDao.updateSelective(pushMessage);
            }
        }
    }

    public void deleteLastDaySuccessMessage() {
        Date lastDay = DateUtils.addDays(new Date(), -1);
        pushMessageDao.deleteLastDaySuccessMessage(lastDay);
    }
}
